﻿package {
	import flash.display.Shape;
	import flash.text.TextField;
	import flash.text.TextFormat;	
	import flash.ui.Mouse;
	
	import fl.managers.StyleManager;	
	
	import flash.events.MouseEvent;	
	
	import adobe.utils.MMExecute;
	
	import fl.controls.Button;
	import fl.controls.CheckBox;
	import fl.controls.ComboBox;
	import fl.controls.TextInput;
	
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.external.ExternalInterface;		
	import flash.utils.describeType;

	/**
	 * TODO:添加库的位图元素的编辑功能.
	 * @author tamt
	 */
	public class LibraryItemInspector extends Sprite {
		//确定按钮
		public var confirm_btn : Button;
		//取消按钮
		public var cancel_btn:Button;
		//应用按钮
		public var apply_btn:Button;
		
		//名称
		public var name_tf : TextInput;
		//类型combobox
		public var type_cb : ComboBox;
		//9切片框
		public var scale9grid_cb : CheckBox;
		//导出AS
		public var exportAS_cb : CheckBox;
		//在第一帧中导出.
		public var exportAt1Frame_cb : CheckBox;
		//类名
		public var className_tf:TextInput;
		//基类名
		public var baseClassName_tf:TextInput;
		//定位
		public var findit_btn:Button;
		
		//当前正在查看的LibraryItem
		private var item:LibraryItem;
		//
		public var debug_tf:TextField;

		public function LibraryItemInspector() {
			super();
			
			addEventListener(Event.ADDED_TO_STAGE, onAdded);
			
			//供jsfl调用的函数
			ExternalInterface.addCallback('showLibrayItemInfo', showLibrayItemInfo);
			ExternalInterface.addCallback('disablePanel', disablePanel);
		}
		
		private function onChangeType(evt:Event):void {
			item.symbolType = ['movie clip', 'button', 'graphic'][type_cb.selectedIndex];
			this.updateView();
		}
		
		private function onChangeExportAS(evt:Event):void {
			item.linkageExportForAS = exportAS_cb.selected;
			if (item.linkageExportForAS) {
				if (item.linkageClassName == 'undefined') {
					item.linkageClassName = item.name;
				}
				if (item.linkageBaseClass == 'undefined') {
					item.linkageBaseClass = LibraryItem.getBaseClassNameByType(item.symbolType);;
				}
				item.linkageExportInFirstFrame = true;
			}
			
			this.updateView();
		}
		
		private function initJSFL():String {
			var xml:XML = <jsfl>
			<![CDATA[
				var panelName = 'Library Item Inspector';
				function showLibrayItemInfo(arg) 
				{ 
					
					if(fl.swfPanels.length > 0){ 
						for(x = 0; x < fl.swfPanels.length; x++){ 
							// look for a SWF panel of the specified name, then call the specified AS3 function 
							// in this example, the panel is named "test" and the AS3 callback is "callMySWF" 
							if(fl.swfPanels[x].name == panelName) // name busted? 
							{ 
								fl.swfPanels[x].call("showLibrayItemInfo",arg); 
								break; 
							} 
						} 
					}
				}
				
				/**
				 * 让Inspector panel面板处于禁用状态
				 */
				function disablePanel() {
					if(fl.swfPanels.length > 0){ 
						for(x = 0; x < fl.swfPanels.length; x++){ 
							if(fl.swfPanels[x].name == panelName) // name busted? 
							{ 
								fl.swfPanels[x].call("disablePanel"); 
								break; 
							} 
						} 
					}
				}

				var item;
				if(fl.getDocumentDOM().selection.length>0){
					var ele = fl.getDocumentDOM().selection[0];
					if (ele.libraryItem) {
						inspectSelection(ele.libraryItem);
					}else {
						disablePanel();
					}
				}else {
					disablePanel();
				}

				function inspectSelection(libraryItem){
					item = libraryItem;
					var name = item.name.substring(item.name.lastIndexOf('/') + 1, item.name.length);
					var arg = '';
					for(var prop in item){
						arg += prop + ':' + item[prop] + '|';
					}
					showLibrayItemInfo(arg);
				}

				fl.addEventListener("mouseMove", onMouseMove);

				function onMouseMove(){
					var ele = fl.getDocumentDOM().selection[0];
					if(ele.libraryItem){
						if(ele.libraryItem.name != item.name)inspectSelection(ele.libraryItem);
					}else {
						disablePanel();
					}
				}

				//定位元素库元件在库中的位置.
				//似乎selectItem(item)在flash cs4 10.0.2下无效
				function findIt(){
					var lbItem = item;
					if(lbItem){
						if(lbItem.name.lastIndexOf('/')>0){
							var pathNames = lbItem.name.split('/');
							var path = '';
							for(var j=0; j<pathNames.length; j++){
								path += (j==0?'':'/') + pathNames[j];
								fl.getDocumentDOM().library.expandFolder(true, false, path);
							}
							
						}
						
						fl.getDocumentDOM().library.selectItem(lbItem.name);
					}
				}
				
				//应用SWFPanel上的属性
				function apply(arg) {
					alert(arg);
					
					var args = arg.split('|');
					for(var i = 0; i<args.length; i++){
						var t = args[i].indexOf(':');
						var prop = args[i].substring(0, t);
						var value = args[i].substring(t + 1);
						
						for (var str in item) {
							if (str == prop) {
								if(prop == 'scalingGrid' || prop == 'linkageExportForAS' || prop == 'linkageExportForRS' || prop == 'linkageExportInFirstFrame') {
									item[prop] = (value == 'true');
								}else{
									item[prop] = value;
								}
								fl.trace('采用新值：' + prop + '-' + value);
								fl.getDocumentDOM().library.updateItem(item.name);
							}
						}
					}
				}
			]]>
			</jsfl>;
			
			return xml.toString();
		}

		private function onAdded(evt:Event):void{
			//this.findit_btn.addEventListener(MouseEvent.CLICK, onClickFindIt);
			//this.confirm_btn.addEventListener(MouseEvent.CLICK, onClickCfm);
			this.apply_btn.addEventListener(MouseEvent.CLICK, onClickApply);
			
			//设置组件样式
			var tfm : TextFormat = new TextFormat('Trebuchet MS', 12);
			tfm.color = 0xffffff;
			StyleManager.setStyle('textFormat', tfm);
			
			exportAS_cb.addEventListener(Event.CHANGE, onChangeExportAS);
			type_cb.addEventListener(Event.CHANGE, onChangeType);
			
			//运行JSFL函数
			MMExecute(initJSFL());
		}
		
		//应用按钮时
		private function onClickApply(evt:MouseEvent):void {
			item.name = name_tf.text;
			item.symbolType = ['movie clip', 'button', 'graphic'][type_cb.selectedIndex];
			item.linkageClassName = className_tf.text;
			item.linkageBaseClass = baseClassName_tf.text
			item.linkageExportForAS = exportAS_cb.selected;
			item.linkageExportInFirstFrame = exportAt1Frame_cb.selected;
			item.scalingGrid = scale9grid_cb.selected;
			
			var pro:String = itemToString(item);
			MMExecute('apply("' + pro + '")');
		}

		private function onClickFindIt(evt:MouseEvent):void {
			MMExecute('findIt();');
		}
		
		private var freezeShape:Sprite;
		private function disablePanel():void {
			this.visible = false;
			if (freezeShape == null) {
				freezeShape = new Sprite();
				freezeShape.graphics.beginFill(0, .2);
				freezeShape.graphics.drawRect(0, 0, this.stage.stageWidth, this.stage.stageHeight);
			}
			//addChild(freezeShape);
		}
		
		private function enablePanel():void {
			this.visible = true;
			if (freezeShape) {
				if (freezeShape.parent) freezeShape.parent.removeChild(freezeShape);
			}
		}

		private function showLibrayItemInfo(arg:String):void {
			enablePanel();
			
			//name:元件 2|type:movie clip|className:元件2
			var args:Array = arg.split('|');
			var obj:Object = {};
			for(var i:int = 0; i<args.length; i++){
				var t:int = args[i].indexOf(':');
				var prop:String = args[i].substring(0, t);
				var value:String = args[i].substring(t + 1);
				obj[prop] = value;
			}
			
			item = new LibraryItem(obj);
			
			updateView();
		}
	
		private function itemToString(item:LibraryItem):String {
			var str:String = '';
			
			var prop:XML;
			for each(prop in (describeType(LibraryItem)..variable.@name)) {
				str += prop.toString() + ':' + item[prop.toString()] + '|';
			}
			
			return str;
		}
		
		private function log(str:String):void {
			debug_tf.text = str;
		}
		
		private function updateView():void {
			name_tf.text = item.name;
			type_cb.selectedIndex = ['movie clip', 'button', 'graphic'].indexOf(item.symbolType);
			
			if (item.symbolType == 'movie clip') {
				scale9grid_cb.enabled = true;
			}else {
				scale9grid_cb.enabled = false;
			}
			if (item.symbolType == 'graphic') {
				exportAS_cb.enabled = false;
				exportAt1Frame_cb.enabled = className_tf.enabled = baseClassName_tf.enabled = false;
				return;
			}else {
				exportAS_cb.enabled = true;
			}
			
			className_tf.text = item.linkageClassName;
			baseClassName_tf.text = item.linkageBaseClass;
			exportAS_cb.selected = item.linkageExportForAS;
			exportAt1Frame_cb.selected = item.linkageExportInFirstFrame;
			scale9grid_cb.selected = item.scalingGrid;
			
			if (!item.linkageExportForAS) {
				exportAt1Frame_cb.enabled = className_tf.enabled = baseClassName_tf.enabled = false;
			}else {
				exportAt1Frame_cb.enabled = className_tf.enabled = baseClassName_tf.enabled = true;
			}
		}
	}
}
import flash.geom.Rectangle;
dynamic class LibraryItem{
	//public var timeline:String;
	public var symbolType:String;
	//public var sourceFilePath:String;
	//public var sourceLibraryName:String;
	//public var sourceAutoUpdate:Boolean;
	public var scalingGrid:Boolean;
	//public var scalingGridRect:Rectangle;
	public var itemType:String;
	public var name:String;
	public var linkageExportForAS:Boolean;
	//public var linkageExportForRS:Boolean;
	public var linkageExportInFirstFrame:Boolean;
	public var linkageIdentifier:String;
	public var linkageClassName:String;
	public var linkageBaseClass:String;
	//public var linkageURL:String;
	
	public function LibraryItem(obj:*):void{
		//timeline = obj.timeline;
		symbolType = obj.symbolType;
		//sourceFilePath = encodeURI(obj.sourceFilePath);
		//sourceLibraryName = obj.sourceLibraryName;
		//sourceAutoUpdate = (obj.sourceAutoUpdate == 'true');
		scalingGrid = (obj.scalingGrid == 'true');
//		scalingGridRect = obj.scalingGridRect;
		itemType = obj.itemType;
		name = obj.name;
		linkageExportForAS = (obj.linkageExportForAS == 'true');
		//linkageExportForRS = (obj.linkageExportForRS == 'true');
		linkageExportInFirstFrame = (obj.linkageExportInFirstFrame == 'true');
		linkageIdentifier = obj.linkageIdentifier;
		linkageClassName = obj.linkageClassName;
		linkageBaseClass = obj.linkageBaseClass;
		//linkageURL = obj.linkageURL;
	}
	
	public static function getBaseClassNameByType(type:String):String {
		var str:String;
		switch(type) {
			case 'movie clip':
				str = 'flash.display.MovieClip';
				break;
			case 'button':
				str = 'flash.display.SimpleButton';
				break;
		}
		return str;
	}
}